package com.masterclient.app.modules.order;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.eoner.baselibrary.bean.goods.ProductBean;
import com.eoner.baselibrary.bean.order.PaySuccessBean;
import com.eoner.baselibrary.bean.order.PresentationShareBean;
import com.eoner.commonbean.popup.CommonPopUpBean;
import com.eoner.common.config.Config;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselibrary.utils.GlideUtil;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.MainActivity;
import com.masterclient.app.R;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.modules.goods.adapter.GoodsRecyclerAdapter;
import com.masterclient.app.modules.order.contract.PaySuccessContract;
import com.masterclient.app.modules.order.contract.PaySuccessPresenter;
import com.masterclient.app.utils.CommonUtil;
import com.masterclient.app.widget.ImageDialog;
import com.masterclient.app.widget.ShareGivingDialog;
import com.masterclient.app.widget.StaggeredGridNoScrollLayoutManager;
import com.umeng.analytics.MobclickAgent;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者：sean
 * 创建时间：2017/8/5 15:37
 * 功能说明：
 */

public class PaySuccessActivity extends BaseActivity<PaySuccessPresenter> implements PaySuccessContract.View {

    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_order_detail)
    TextView tvOrderDetail;
    @BindView(R.id.tv_guang)
    TextView tvGuang;
//    @BindView(R.id.goodsGridLayout)
//    GridLayout goodsGridLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.ll_pay)
    LinearLayout llPay;
    @BindView(R.id.tv_partner_adv)
    TextView tv_partner_adv;
    @BindView(R.id.ll_partner)
    LinearLayout llPartner;
    @BindView(R.id.ll_normal)
    LinearLayout llNormal;
    @BindView(R.id.ll_groupbuy)
    LinearLayout llGroupbuy;
    @BindView(R.id.pay_success_bg)
    ImageView paySuccessBg;
    @BindView(R.id.iv_vip)
    ImageView ivVip;
    @BindView(R.id.tv_share)
    TextView tv_share;

    String trade_no, is_group_buy, order_no;
    String is_offline;
    RxBus rxBus;
    @BindView(R.id.tv_vip_center)
    TextView tvVipCenter;
    private String url, title, convert, saleType, relationOrderId;

    private GoodsRecyclerAdapter goodRecyclerAdapter;
    private List<ProductBean> productsBeanList ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_success);
        ButterKnife.bind(this);
        trade_no = getBundleString("trade_no");
        is_group_buy = getBundleString("is_group_buy");
        convert = getBundleString("convert");
        saleType = getBundleString("sale_type");
        relationOrderId = getBundleString("relation_order_id");//提货代发订单号

        if ("4".equals(saleType) || "6".equals(saleType)){
            tvGuang.setTextColor(Color.parseColor("#FF6809"));
            tvGuang.setBackgroundResource(R.drawable.shape_round_line_ff6809);
            if ("6".equals(saleType)){
                tvGuang.setText(TextUtils.isEmpty(relationOrderId)?"继续提货":"\u3000返回\u3000");
            }
        }

        StaggeredGridNoScrollLayoutManager layoutManager = new StaggeredGridNoScrollLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(null);
        goodRecyclerAdapter = new GoodsRecyclerAdapter();
        recyclerView.setAdapter(goodRecyclerAdapter);
        goodRecyclerAdapter.bindToRecyclerView(recyclerView);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.set(ScreenUtils.dp2px(4), ScreenUtils.dp2px(9), ScreenUtils.dp2px(5), 0);
            }
        });

        if ("1".equals(getBundleString("is_join_partner"))) {
            tv_partner_adv.setVisibility(View.VISIBLE);
            llPartner.setVisibility(View.VISIBLE);
            llNormal.setVisibility(View.GONE);
            llGroupbuy.setVisibility(View.GONE);
        } else if ("1".equals(is_group_buy)) {
            tv_partner_adv.setVisibility(View.VISIBLE);
            tv_partner_adv.setText("恭喜您成功开团！");
            llGroupbuy.setVisibility(View.VISIBLE);
            llPartner.setVisibility(View.GONE);
            llNormal.setVisibility(View.GONE);
        } else {
            tv_partner_adv.setVisibility(View.GONE);
            llPartner.setVisibility(View.GONE);
            llGroupbuy.setVisibility(View.GONE);
            llNormal.setVisibility(View.VISIBLE);
        }

        mPresenter.paySuccess(trade_no, convert);
        rxBus = RxBus.$();

        if ("4".equals(convert)) {
            tvVipCenter.setVisibility(View.VISIBLE);
            tvGuang.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.tv_vip_center,R.id.pay_success_bg, R.id.tv_groupbuy_detail, R.id.tv_guangguang,
            R.id.rl_back, R.id.tv_order_detail, R.id.tv_guang, R.id.tv_order, R.id.tv_to_partner,R.id.tv_share})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.pay_success_bg:
                if (TextUtils.isEmpty(url)) {
                    return;
                }
                startActivitry(BridgeActivity.class, new String[][]{{"url", url}, {"title", title}});
                break;
            case R.id.tv_guangguang:
                rxBus.post(Config.SWITCH, Config.GO_RECOMMENT);
                startActivitry(MainActivity.class, new String[][]{{"position", "0"}});
                finish();
                break;
            case R.id.tv_vip_center:
                startActivitry(MainActivity.class, new String[][]{{"position", "2"}});
                finish();
                break;
            case R.id.rl_back:
                finish();
                break;
            case R.id.tv_order_detail:
            case R.id.tv_order:
                if ("1".equals(is_offline)) {
                    startActivitry(CustomerOrderActivity.class, new String[][]{{"position", "0"}});
                    finish();
                } else {
                    if ("4".equals(saleType) || "6".equals(saleType)) {

                        ARouter.getInstance().build(AroutePath.PURCHASE_ORDERS_ACTIVITY)
                                .withInt("position",2)
                                .withString("from_type","purchase").navigation();
                    }else {
                        Intent broadcast = new Intent();
                        broadcast.setAction("refreshUnComemtedFagment");
                        mContext.sendBroadcast(broadcast);
                        startActivitry(CustomerOrderActivity.class, new String[][]{{"position", "2"}});
                    }
                    finish();
                }
                break;
            case R.id.tv_to_partner:
                startActivitry(MainActivity.class, new String[][]{{"position", "2"}});
                break;
            case R.id.tv_guang:
                if (!"6".equals(saleType)){
                    rxBus.post(Config.SWITCH, Config.GO_RECOMMENT);
                    startActivitry(MainActivity.class, new String[][]{{"position", "0"}});
                }
                finish();
                break;
            case R.id.tv_share: {
                //调接口 (ShareCommonDialog)
                mPresenter.getShareData(order_no);
            }
                break;
        }
    }

    @Override
    protected void onResume() {
        MobclickAgent.onEvent(mContext, "click_place_order");
        super.onResume();
    }

    @Override
    public void getPaySuccess(PaySuccessBean.DataBean bean) {

        if (bean != null && bean.getSh_pop_msg() != null && !"0".equals(bean.getSh_pop_msg().getSh_location())){
            mPresenter.getPopUpData("pay", bean.getSh_pop_msg().getSh_location(),trade_no);
        }

        if (bean!=null && bean.isSh_display_share()) {
            tv_share.setVisibility(View.VISIBLE);
            tvGuang.setVisibility(View.GONE);
        } else {
            tv_share.setVisibility(View.GONE);
            tvGuang.setVisibility(View.VISIBLE);
        }

        if ("4".equals(convert)) {
            tv_partner_adv.setVisibility(View.VISIBLE);
            tv_partner_adv.setText(bean.getSh_message());
        }

        //vip图片显示
        if (bean.getSh_upgrade_to_vip() != null && !TextUtils.isEmpty(bean.getSh_upgrade_to_vip().getSh_target())){
            ivVip.setVisibility(View.VISIBLE);
            int width;
            if (Integer.parseInt(bean.getSh_upgrade_to_vip().getSh_height()) > Integer.parseInt(bean.getSh_upgrade_to_vip().getSh_height())) {
                width = (int) (ScreenUtils.getScreenWidth() * 0.915);
            } else {
                width = (int) (ScreenUtils.getScreenWidth() * 0.915);
            }

            double height = div(Double.parseDouble(bean.getSh_upgrade_to_vip().getSh_height()), Double.parseDouble(bean.getSh_upgrade_to_vip().getSh_width()), 2) * width;
            ViewGroup.LayoutParams params = ivVip.getLayoutParams();
            params.width = width;
            params.height = (int) height;
            ivVip.setLayoutParams(params);
            Glide.with(mContext).load(bean.getSh_upgrade_to_vip().getSh_icon()).into(ivVip);
            ivVip.setOnClickListener(view -> {
                CommonUtil.goAnyWhere(this, bean.getSh_upgrade_to_vip().getSh_target(), "", "", "", "");
            });
        }else {
            ivVip.setVisibility(View.GONE);
        }

        paySuccessBg.getLayoutParams().height = (int) ((ScreenUtils.getScreenWidth()-ScreenUtils.dp2px(30))*7/34.0f);
        if (bean != null && bean.getSh_banner() != null && !TextUtils.isEmpty(
                bean.getSh_banner().getSh_img()) && !TextUtils.isEmpty(bean.getSh_banner().getSh_url())) {
//            App.picasso.load(bean.getSh_banner().getSh_img()).error(R.mipmap.defaults_1).placeholder(R.mipmap.defaults_1)
//                    .into(paySuccessBg);
            GlideUtil.displayImage(getActivity(),bean.getSh_banner().getSh_img(),paySuccessBg,R.mipmap.defaults_1);
            paySuccessBg.setVisibility(View.VISIBLE);
            url = bean.getSh_banner().getSh_url();
            title = bean.getSh_banner().getSh_title();
        }

        tvPrice.setText("¥" + bean.getSh_subtotal());
        is_offline = bean.getSh_is_offline();
        if ("1".equals(is_group_buy)) {
            tv_partner_adv.setText(bean.getSh_is_join_text());
        }
        order_no = bean.getSh_order_no();
        if (bean.getSh_products() != null) {
            productsBeanList = bean.getSh_products();
            goodRecyclerAdapter.setNewData(productsBeanList);
        }
    }

    @Override
    public void getPaySuccessFailed(String msg) {
        showToast(msg);
    }

    @Override
    public void getDialogSuccess(List<CommonPopUpBean> dataBean) {
        if (dataBean != null && dataBean.size()>0 && !TextUtils.isEmpty(dataBean.get(0).getImage())) {
            String target = dataBean.get(0).getTarget();
            String targetId = dataBean.get(0).getTarget_id();
            new ImageDialog("支付成功页", getActivity(), dataBean.get(0).getImage(), target, targetId,
                    "", new ImageDialog.OnChooseListerner() {
                @Override
                public void cancel() {

                }

                @Override
                public void confirm() {
                    finish();
                }
            }).show();
        }
    }

    @Override
    public void getShareDataSuccess(PresentationShareBean shareBean) {
        ShareGivingDialog givingDialog = new ShareGivingDialog(getActivity());
        givingDialog.show();
        givingDialog.shareZsqDetail(shareBean);
    }

    /**
     * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指
     * 定精度，以后的数字四舍五入。
     *
     * @param v1    被除数
     * @param v2    除数
     * @param scale 表示表示需要精确到小数点以后几位。
     * @return 两个参数的商
     */
    private double div(double v1, double v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public interface OnItemChildClickListener {
        void getPosition(String id, int data_position, int position, ArrayList<String> imageList, ArrayList<String> imageWidthList, ArrayList<String> imageHeightList);
    }

}
